<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.title"
        placeholder="文章标题"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter="handleFilter"
      />
      <el-select v-model="listQuery.status" placeholder="状态" clearable style="width: 120px" class="filter-item">
        <el-option v-for="item in statusOptions" :key="item.key" :label="item.display_name" :value="item.key" />
      </el-select>
      <el-select v-model="listQuery.categoryId" placeholder="分类" clearable style="width: 120px" class="filter-item">
        <el-option v-for="item in categoryOptions" :key="item.id" :label="item.name" :value="item.id" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="Search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="Plus" @click="handleCreate">
        添加文章
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80">
        <template #default="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="标题" min-width="200px" align="center">
        <template #default="{row}">
          <span class="link-type" @click="handleUpdate(row)">{{ row.title }}</span>
        </template>
      </el-table-column>
      <el-table-column label="作者" width="120px" align="center">
        <template #default="{row}">
          <span>{{ row.author }}</span>
        </template>
      </el-table-column>
      <el-table-column label="分类" width="100px" align="center">
        <template #default="{row}">
          <span>{{ row.category }}</span>
        </template>
      </el-table-column>
      <el-table-column label="标签" width="150px" align="center">
        <template #default="{row}">
          <el-tag v-for="tag in row.tags" :key="tag" size="small" style="margin-right: 5px;">
            {{ tag }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100px" align="center">
        <template #default="{row}">
          <el-tag :type="row.status | statusFilter">
            {{ row.status | statusDisplayFilter }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="阅读量" width="100px" align="center">
        <template #default="{row}">
          <span>{{ row.viewCount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="150px" align="center">
        <template #default="{row}">
          <span>{{ parseTime(row.createTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="280" class-name="small-padding fixed-width">
        <template #default="{row,$index}">
          <el-button type="primary" size="small" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button v-if="row.status!=='published'" size="small" type="success" @click="handleModifyStatus(row,'published')">
            发布
          </el-button>
          <el-button v-if="row.status!=='draft'" size="small" @click="handleModifyStatus(row,'draft')">
            下架
          </el-button>
          <el-button size="small" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.current" :limit.sync="listQuery.pageSize" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" v-model="dialogFormVisible" width="80%">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="文章标题" prop="title">
              <el-input v-model="temp.title" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="作者" prop="author">
              <el-input v-model="temp.author" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="分类" prop="categoryId">
              <el-select v-model="temp.categoryId" placeholder="请选择分类" style="width: 100%">
                <el-option v-for="item in categoryOptions" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="标签" prop="tags">
              <el-select v-model="temp.tags" multiple placeholder="请选择标签" style="width: 100%">
                <el-option v-for="item in tagOptions" :key="item.id" :label="item.name" :value="item.name" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="摘要" prop="summary">
          <el-input v-model="temp.summary" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input v-model="temp.content" type="textarea" :rows="10" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">
            取消
          </el-button>
          <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination/index.vue'

const tableKey = ref(0)
const list = ref([])
const total = ref(0)
const listLoading = ref(true)
const listQuery = reactive({
  current: 1,
  pageSize: 20,
  title: undefined,
  status: undefined,
  categoryId: undefined
})

const temp = reactive({
  id: undefined,
  title: '',
  author: '',
  categoryId: undefined,
  tags: [],
  summary: '',
  content: ''
})

const dialogFormVisible = ref(false)
const dialogStatus = ref('')
const textMap = {
  update: '编辑文章',
  create: '创建文章'
}

const rules = {
  title: [{ required: true, message: '文章标题是必填项', trigger: 'blur' }],
  author: [{ required: true, message: '作者是必填项', trigger: 'blur' }],
  categoryId: [{ required: true, message: '分类是必填项', trigger: 'change' }],
  content: [{ required: true, message: '内容是必填项', trigger: 'blur' }]
}

const statusOptions = [
  { key: 'published', display_name: '已发布' },
  { key: 'draft', display_name: '草稿' },
  { key: 'deleted', display_name: '已删除' }
]

const categoryOptions = ref([
  { id: 1, name: '前端开发' },
  { id: 2, name: '后端开发' },
  { id: 3, name: '移动开发' },
  { id: 4, name: '人工智能' }
])

const tagOptions = ref([
  { id: 1, name: 'Vue' },
  { id: 2, name: 'React' },
  { id: 3, name: 'JavaScript' },
  { id: 4, name: 'TypeScript' },
  { id: 5, name: 'Node.js' },
  { id: 6, name: 'Python' }
])

// 状态过滤器
const statusFilter = computed(() => {
  return (status) => {
    const statusMap = {
      published: 'success',
      draft: 'info',
      deleted: 'danger'
    }
    return statusMap[status]
  }
})

const statusDisplayFilter = computed(() => {
  return (status) => {
    const statusMap = {
      published: '已发布',
      draft: '草稿',
      deleted: '已删除'
    }
    return statusMap[status]
  }
})

onMounted(() => {
  getList()
})

function getList() {
  listLoading.value = true
  // 模拟数据
  setTimeout(() => {
    list.value = [
      {
        id: 1,
        title: 'Vue 3.0 新特性详解',
        author: '张三',
        category: '前端开发',
        tags: ['Vue', 'JavaScript'],
        status: 'published',
        viewCount: 1234,
        createTime: new Date()
      },
      {
        id: 2,
        title: 'React Hooks 最佳实践',
        author: '李四',
        category: '前端开发',
        tags: ['React', 'JavaScript'],
        status: 'draft',
        viewCount: 567,
        createTime: new Date()
      },
      {
        id: 3,
        title: 'Node.js 性能优化指南',
        author: '王五',
        category: '后端开发',
        tags: ['Node.js', 'JavaScript'],
        status: 'published',
        viewCount: 890,
        createTime: new Date()
      }
    ]
    total.value = 3
    listLoading.value = false
  }, 1000)
}

function handleFilter() {
  listQuery.current = 1
  getList()
}

function handleModifyStatus(row, status) {
  ElMessage({
    message: '操作成功',
    type: 'success'
  })
  row.status = status
}

function resetTemp() {
  temp.id = undefined
  temp.title = ''
  temp.author = ''
  temp.categoryId = undefined
  temp.tags = []
  temp.summary = ''
  temp.content = ''
}

function handleCreate() {
  resetTemp()
  dialogStatus.value = 'create'
  dialogFormVisible.value = true
}

function handleUpdate(row) {
  temp.id = row.id
  temp.title = row.title
  temp.author = row.author
  temp.categoryId = row.categoryId
  temp.tags = row.tags
  temp.summary = row.summary
  temp.content = row.content
  dialogStatus.value = 'update'
  dialogFormVisible.value = true
}

function createData() {
  ElMessage({
    message: '创建成功',
    type: 'success'
  })
  dialogFormVisible.value = false
  getList()
}

function updateData() {
  ElMessage({
    message: '更新成功',
    type: 'success'
  })
  dialogFormVisible.value = false
  getList()
}

function handleDelete(row, index) {
  ElMessageBox.confirm('此操作将永久删除该文章, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    list.value.splice(index, 1)
    ElMessage({
      type: 'success',
      message: '删除成功!'
    })
  })
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.filter-container {
  padding-bottom: 10px;
  
  .filter-item {
    display: inline-block;
    vertical-align: middle;
    margin-bottom: 10px;
    margin-right: 10px;
  }
}

.link-type {
  color: #409EFF;
  cursor: pointer;
  
  &:hover {
    color: #66b1ff;
  }
}
</style>